/* 06-prod-cons.c

   Producer-consumer co-routining.  There are five producers and four 
   consumers.  Two successors put consecutive numbers into their respective 
   streams.  Two times consumers multiply all consumed numbers by 5 and 3
   respectively and put the results into their streams.  A merge consumer
   merges the two stream created by the times producers.  A consumer prints 
   tokens from the merge stream.  This  illustrates that producer-consumer 
   relationships can be formed into complex networks.

                              3,6,9,12...                1,2,3,4...
                                     /--- Times 3 <---- successor
                      3,5,6,9...    /
          consumer <--- merge <----<
                                    \
                                     \--- Times 5 <---- successor
                              5,10,15,20...              1,2,3,4...
*/
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

int idcnt = 1;

/* One of these per stream.
   Holds:  the mutex lock and notifier condition variables
           a 'value' taken from a producer
           a variable 'available' indicating a token can be consumed
           a structure with information regarding the processing of tokens 
           an identity
*/
typedef struct stream_struct {
   struct stream_struct *next;  /* support a linked list of streams */
   pthread_mutex_t lock;
   pthread_cond_t notifier;
   void *value;
   bool available;
   void *args;                  /* arguments for the producing stream */
   int id;
} Stream;

/* prod: a linked list of streams that a producer consumes tokens from
   self: the producer's output stream  */
typedef struct {
   Stream *prod, *self;
} Args;

/* return 'value' which should have a value from a call to put */
void *get(void *stream) {
   void *ret;

   bool available = ((Stream*)stream)->available;
   pthread_mutex_t *lock = &((Stream*)stream)->lock;
   pthread_cond_t *notifier = &((Stream*)stream)->notifier;
   
   pthread_mutex_lock(lock);    /* lock other threads out of this section    */
   if (!available)              /* if nothing in the buffer, wait and open   */
      pthread_cond_wait(notifier, lock);     /* the section to other threads */
   ((Stream*)stream)->available = false;     /* the token has been consumed  */
   ret = ((Stream*)stream)->value;           /* the token to be consumed     */
   pthread_cond_signal(notifier);  /* wake up sleeping producer, if any      */
   pthread_mutex_unlock(lock);  /* unlock the section */

   return ret;
}

/* 'value' is the value to move to the consumer */
void put(void *stream, void *value) {
   bool available = ((Stream*)stream)->available;
   pthread_mutex_t *lock = &((Stream*)stream)->lock;
   pthread_cond_t *notifier = &((Stream*)stream)->notifier;
   
   pthread_mutex_lock(lock);       /* lock the section */
   if (available)                  /* if a token is waiting for consumption  */
      pthread_cond_wait(notifier, lock);   /* put this thread to sleep       */
   ((Stream*)stream)->available = true;  /* a token is ready for consumption */
   ((Stream*)stream)->value = value;  /* this is the token to be consumed    */
   pthread_cond_signal(notifier);     /* wake up a sleeping consumer, if any */
   pthread_mutex_unlock(lock);     /* unlock the section */

   return;
}

/* Put 1,2,3,4,5... into the self stream */
void *successor (void *streams) {
   Stream *self = ((Args*)streams)->self;
   int id = ((Args*)streams)->self->id;
   int i;
   
   for (i=1 ; ; i++) {
      printf("Successor(%d): sending %d\n", id, i);
      put(self, (void*)i);
      printf("Successor(%d): sent %d\n", id, i);
   }
   pthread_exit(NULL);
}

/* multiply all tokens from the self stream by (int)self->args and insert
   the resulting tokens into the self stream */
void *times (void *streams) {
   Stream *self = ((Args*)streams)->self;
   Stream *prod = ((Args*)streams)->prod;
   int i, value, in;
   
   printf("Times(%d) connected to Successor (%d)\n", self->id, prod->id);
   while (true) {
      int in = (int)get(prod);
      value = in * (int)(self->args);
      printf("\t\tTimes(%d): got %d from Successor %d\n",self->id,in,prod->id);
      put(self, (void*)value);
      printf("\t\tTimes(%d): sent %d\n", self->id, value);
   }
   pthread_exit(NULL);
}

/* merge two streams that containing tokens in increasing order 
   ex: stream 1:  3,6,9,12,15,18...  stream 2: 5,10,15,20,25,30...
       output stream: 3,5,6,9,10,12,15,15,18...
*/
void *merge (void *streams) {
   Stream *self = ((Args*)streams)->self;
   Stream *s1 = ((Args*)streams)->prod;
   Stream *s2 = (((Args*)streams)->prod)->next;
   void *a = get(s1);
   void *b = get(s2);

   while (true) {
      if (a < b) {
         put(self, a);
         a = get(s1);
         printf("\t\t\t\t\tMerge(%d): sent %d from Times %d\n", 
                self->id, (int)a, s1->id);
      } else {
         put(self, b);
         b = get(s2);
         printf("\t\t\t\t\tMerge(%d): sent %d from Times %d\n", 
                self->id, (int)b, s2->id);
      }
   }
   pthread_exit(NULL);
}

/* Final consumer in the network */
void *consumer (void *streams) {
   Stream *prod = ((Args*)streams)->prod;
   int i, value;
   
   for (i=0 ; i < 10 ; i++) 
      printf("\t\t\t\t\t\t\tConsumer: got %d\n", (int)get(prod));
   
   pthread_exit(NULL);
}

/* initialize streams - see also queue_a.h and queue_a.c */
void init_stream (Args *args, Stream *self, void *data) {
   if (self != NULL) {
      self->available = false;
      self->value = NULL;
      self->next = NULL;
      self->args = data;
      self->id = idcnt++;
      pthread_mutex_init(&self->lock, NULL);
      pthread_cond_init (&self->notifier, NULL);
   }
   args->self = self;
   args->prod = NULL;
}

/* puts an initialized stream object onto the end of a stream's input list */
void connect (Args *arg, Stream *s) {  
   s->next = arg->prod;
   arg->prod = s;
}

int main () {
   pthread_t s1, s2, t1, t2, m1, c1;
   Stream suc1, suc2, tms1, tms2, mrg, cons;
   Args suc1_args, suc2_args, tms1_args, tms2_args, mrg_args, cons_args;
   pthread_attr_t attr;

   init_stream(&suc1_args, &suc1, NULL);   /* initialize a successor stream */

   init_stream(&suc2_args, &suc2, NULL);   /* initialize a successor stream */

   init_stream(&tms1_args, &tms1, (void*)3); /* initialize a times 3 stream */
   connect(&tms1_args, &suc1);               /* connect to a successor */

   init_stream(&tms2_args, &tms2, (void*)5); /* initialize a times 5 stream */
   connect(&tms2_args, &suc2);               /* connect to a successor */

   init_stream(&mrg_args, &mrg, NULL);     /* initialize a merge stream */
   connect(&mrg_args, &tms1);              /* connect to a times stream */
   connect(&mrg_args, &tms2);              /* connect to a 2nd times stream */

   init_stream(&cons_args, NULL, NULL);    /* initialize a consumer stream */
   connect(&cons_args, &mrg);              /* connect to a merge stream */

   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
   pthread_create(&s1, &attr, successor, (void*)&suc1_args);
   pthread_create(&s2, &attr, successor, (void*)&suc2_args);
   pthread_create(&t1, &attr, times, (void*)&tms1_args);
   pthread_create(&t2, &attr, times, (void*)&tms2_args);
   pthread_create(&m1, &attr, merge, (void*)&mrg_args);
   pthread_create(&c1, &attr, consumer, (void*)&cons_args);

   pthread_join(c1, NULL);    /* cancel all running threads when the */
                              /* is finished consuming */
   pthread_cancel(s1);
   pthread_cancel(s2);
   pthread_cancel(t1);
   pthread_cancel(t2);
   pthread_cancel(m1);

   pthread_exit(NULL);
}
   
